package tps12.axwax.server;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONStringer;
import org.json.JSONWriter;

import tps12.axwax.server.util.CompatibleHttpServlet;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class LoginServlet extends CompatibleHttpServlet {
	
	final Logger log = Logger.getLogger(LoginServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		resp.setContentType("application/json");
	    UserService userService = UserServiceFactory.getUserService();
	    User user = userService.getCurrentUser();

	    String url = URLDecoder.decode(req.getQueryString().split("=")[1], "UTF-8");
	    
		try {
			JSONWriter w = new JSONStringer()
				.object()
					.key("loggedin").value(user != null)
					.key("admin").value(user != null && userService.isUserAdmin())
					.key("url").value(user != null ?
							userService.createLogoutURL(url) :
							userService.createLoginURL(url))
					.key("name").value(user != null ? user.getNickname() : "")
				.endObject();
			resp.getWriter().println(w.toString());
		}
		catch (JSONException e) { 
			log.log(Level.SEVERE, "Creating JSON representation of login data failed", e);
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}
}
